<template>
  <div class="container">
    <div class="mb10">
      <el-text class="mx-1"> 查询条件：</el-text>
    </div>
    <el-row :gutter="10">
      <el-col :xl="6" :lg="6" :md="12" :sm="24">
        <el-input v-model.trim="searchCondition.company_name" placeholder="营业执照名称" clearable></el-input>
      </el-col>
      <el-col :xl="6" :lg="6" :md="12" :sm="24">
        <el-input v-model.trim="searchCondition.name" placeholder="联系人名称" clearable></el-input>
      </el-col>
      <el-col :xl="6" :lg="6" :md="12" :sm="24">
        <el-input v-model.trim="searchCondition.mobile" placeholder="手机号" clearable></el-input>
      </el-col>
      <el-col :xl="6" :lg="6" :md="12" :sm="24">
        <el-select v-model="searchCondition.status" clearable placeholder="请选择通过状态">
          <el-option v-for="item in statusList" :key="item.id" :label="item.dictLabel" :value="item.dictValue"> </el-option>
        </el-select>
      </el-col>
      <el-col :xl="6" :lg="6" :md="12" :sm="24">
        <el-space wrap>
          <el-button type="success" :icon="Search" :disabled="disabledbtn" @click="searchInfo">搜索</el-button>
          <el-button type="warning" :icon="Refresh" :disabled="disabledbtn" @click="resetSearch">重置</el-button>
        </el-space>
      </el-col>
    </el-row>
    <div class="mb10">
      <el-text class="mx-1"> 查询结果：</el-text>
    </div>
    <el-space wrap class="mb20">
      <el-button type="primary" :icon="Plus" :disabled="disabledbtn" @click="changeFormStatus('add')" v-permission="'add'">新增</el-button>
      <!-- <el-popconfirm placement="top" width="160" title="你确定要删除吗?" @confirm="batchDelete">
        <template #reference>
          <el-button type="danger" :icon="Delete" :disabled="disabledbtn">批量删除 </el-button>
        </template>
      </el-popconfirm> -->
    </el-space>
    <el-table :data="tableList" border class="table" row-key="id" ref="multipleTableRef" v-loading="loading" :reserve-selection="true" @row-dblclick="rowDblclick">
      <el-table-column type="index" align="center"> </el-table-column>
      <el-table-column type="selection" width="55" align="center"></el-table-column>
      <el-table-column prop="company_name" label="营业执照名称" align="center"> </el-table-column>
      <el-table-column prop="name" label="联系人" align="center"> </el-table-column>
      <el-table-column prop="mobile" label="手机号" align="center"> </el-table-column>
      <el-table-column prop="expect_investment_amount" label="预计投资金额" align="center"> </el-table-column>
      <el-table-column prop="expect_investment_time" label="预计投资时间" align="center" :formatter="(row: IInvestorsInfoVo) => handleVerifyFormatDate(Number(row.expect_investment_time))"> </el-table-column>
      <el-table-column prop="enterprise_alipay_account" label="企业支付宝帐号" align="center"> </el-table-column>
      <el-table-column prop="zft_status_name" label="直付通审核状态" align="center"> </el-table-column>
      <el-table-column prop="status_name" label="通过状态" align="center">
        <template #default="scope">
          <div class="w-tag">
            <el-tag :type="scope.row.status === 'approved' ? 'success' : scope.row.status === 'in_application' ? 'primary' : scope.row.status === 'forbid' ? 'warning' : scope.row.status === 'reject' ? 'danger' : 'primary'">{{ scope.row.status_name }}</el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="210" align="center">
        <template #default="scope">
          <div class="control-flex">
            <!-- <el-button type="primary"  link :icon="View" @click="handleViewEdit(scope.row, 'view')">查看</el-button> -->
            <el-button type="primary" link :icon="EditPen" v-permission="'edit'" @click="handleViewEdit(scope.row, 'edit')">编辑</el-button>
            <el-dropdown>
              <span class="el-dropdown-link">
                更多操作<el-icon class="el-icon--right">
                  <arrow-down />
                </el-icon>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item>
                    <el-button type="primary" link :icon="View" class="w100-t-a-l" @click="handleViewEdit(scope.row, 'view')">查看 </el-button>
                  </el-dropdown-item>
                  <el-dropdown-item>
                    <el-button type="primary" link :icon="View" class="w100-t-a-l" @click="handleToControlConsoleInfo(scope.row)">查看数据 </el-button>
                  </el-dropdown-item>
                  <el-dropdown-item v-if="![null, ''].includes(scope.row.contract_url)">
                    <el-button type="primary" link :icon="View" @click="handleViewContractInfo(scope.row.contract_url)">查看合同 </el-button>
                  </el-dropdown-item>
                  <el-dropdown-item v-if="['approved'].includes(scope.row.status)">
                    <el-button type="primary" link :icon="Plus" class="w100-t-a-l" @click="handleAddInvestorMoneyLog(scope.row)">新增资金记录 </el-button>
                  </el-dropdown-item>
                  <el-dropdown-item v-if="['approved'].includes(scope.row.status) && [''].includes(scope.row.zft_status)">
                    <el-button type="primary" link :icon="Plus" class="w100-t-a-l" @click="handleAddZFTInfo(scope.row)">入驻直付通 </el-button>
                  </el-dropdown-item>
                  <el-dropdown-item v-if="['approved'].includes(scope.row.status) && ['99', '-1'].includes(scope.row.zft_status)">
                    <el-button type="primary" link :icon="EditPen" class="w100-t-a-l" @click="handleUpdateZFTInfo(scope.row)">修改直付通资料 </el-button>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
            <!-- <div v-permission="'delete'">
              <el-popconfirm placement="top" width="160" title="你确定要删除吗?" @confirm="deleteInfo([scope.row.id])">
                <template #reference>
                  <el-button link :icon="Delete"  type="danger">删除</el-button>
                </template>
              </el-popconfirm>
            </div> -->
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination
        background
        @update:current-page="handleCurrentChange"
        @update:page-size="handleSizeChange"
        layout="total, sizes, prev, pager, next, jumper"
        :page-size="searchCondition.size"
        :current-page="searchCondition.current"
        :page-sizes="[10, 20, 30, 40, 50, 100]"
        :total="total"
        :hide-on-single-page="false">
      </el-pagination>
    </div>
    <InvestorMoneyDialog v-model:editVisible="investorMoneyVisible" v-model:form="investorMoneyForm" />
  </div>
</template>

<script setup lang="ts">
import InvestorMoneyDialog from "@/components/user/investorsManager/investorsInfo/InvestorMoneyDialog.vue";
import { View, EditPen, Search, Refresh, Plus } from "@element-plus/icons-vue";
import { handleVerifyFormatDate } from "@/utils/utils";
import type { ViewMode, ViewModeFilter } from "@/types/common";
import { useState } from "@/hooks/useState.ts";
import type { IInvestorsInfoVo, ISearchInvestorsInfo } from "@/types/user/investorsInfo";
import { getInvestorsList, putMerchantZftCreateInfo, putMerchantZftModifyInfo } from "@/utils/api/admin/merchant/investors";
import type { IDictData } from "@/types/dict";
import { IMG_URL } from "@/utils/config";
import type { IInvestorsMoneyLogInfoDTO } from "@/types/user/investorMoneyLogInfo";
interface Props {
  statusList: Array<IDictData>;
}
const { statusList } = defineProps<Props>();
const { disabledbtn, loading, toggleState } = useState();

const emit = defineEmits<{
  handleAdd: [code: ViewMode];
  handleViewEdit: [id: number, code: ViewModeFilter];
}>();
/* 暴露一个方法给父组件使用 */
defineExpose({
  /* 这一步关键，在setup语法糖中使用时 */
  getTableInfo
});
const multipleTableRef = useTemplateRef("multipleTableRef"); /* 列表组件的引用 */

const total = ref(0);
const investorMoneyVisible = ref(false);
const searchCondition = reactive<ISearchInvestorsInfo>({
  name: "",
  company_name: "",
  status: "",
  mobile: "",
  current: 1,
  size: 10
});
const tableList = ref<Array<IInvestorsInfoVo>>([]);

/* 新增投资商资金 */
const investorMoneyForm = reactive<IInvestorsMoneyLogInfoDTO>({
  investor_id: 0,
  money: "",
  operation_time: "",
  remark: "",
  type: ""
});

onMounted(() => {
  getTableInfo();
});
/* 搜索 */
function searchInfo() {
  searchCondition.current = 1;
  searchCondition.size = 10;
  getTableInfo();
}

/**
 * 重置搜索内容
 */
function resetSearch() {
  searchCondition.name = "";
  searchCondition.company_name = "";
  searchCondition.status = "";
  searchCondition.mobile = "";
  searchCondition.current = 1;
  searchCondition.size = 10;

  getTableInfo();
}

/**
 * 切换表单状态（ 添加、编辑、查看 ，隐藏none ）
 */
function changeFormStatus(state: ViewMode) {
  // formStatus.value = state;
  emit("handleAdd", state);
}

/* 请求：获取表格中数据 */
function getTableInfo() {
  toggleState(true);
  getInvestorsList<IInvestorsInfoVo, ISearchInvestorsInfo>(searchCondition)
    .then(res => {
      tableList.value = res.result.data;
      total.value = res.result.total;
    })
    .finally(() => {
      toggleState(false);
    });
}

/* 显示第几页 */
function handleCurrentChange(val: number) {
  searchCondition.current = val;
  getTableInfo();
}

/* 每页显示几条 */
function handleSizeChange(val: number) {
  searchCondition.current = 1;
  searchCondition.size = val;
  getTableInfo();
}

/* 触发处理 查看编辑事件 */
function handleViewEdit(row: IInvestorsInfoVo, code: ViewModeFilter) {
  emit("handleViewEdit", row.id, code);
}

/* 双击当前行 */
function rowDblclick(row: IInvestorsInfoVo) {
  multipleTableRef.value!.toggleRowSelection(row);
}

// /* 批量删除 */
// function batchDelete() {
//   /* 获取选中的数据 */
//   let selection = multipleTableRef.value!.store.states.selection.value;
//   if (selection.length === 0) {
//     ElMessage.warning("请至少选择一条数据");
//     return;
//   }
//   let idArray = [];
//   for (const item of selection) {
//     idArray.push(item.id);
//   }
//   deleteInfo(idArray);
// }
// /* 删除后的信息 */
// function deleteInfo(idArray: Array<number>) {
//   toggleState(true);
//   deleteMallRedPacketPurchaseInfo({ idArray })
//     .then(() => {
//       /* 当删除成功后，删除对应选中的数据或单个数据 */
//       tableList.value = tableList.value.filter((item: IInvestorsInfoVo) => !idArray.includes(item.id));
//       ElMessage.success(`成功删除了${idArray.length}条数据`);
//       multipleTableRef.value!.clearSelection();
//       total.value = total.value - idArray.length;
//     })
//     .catch((error: Error) => {
//       console.log(error);
//     })
//     .finally(() => {
//       toggleState(false);
//     });
// }
/* 跳转到平台数据 */
function handleToControlConsoleInfo(row: IInvestorsInfoVo) {
  console.log(row);
  ElMessage.success("敬请期待");
  // this.Common.toBlankPage("/controlConsoleInfo", { investor_id: row.id });
}

/* 查看合同 */
function handleViewContractInfo(url: string) {
  window.open(IMG_URL + url, "_blank");
}
/* 新增资金记录 */
function handleAddInvestorMoneyLog(row: IInvestorsInfoVo) {
  investorMoneyVisible.value = true;
  investorMoneyForm.investor_id = row.id;
}
/* 投资商入驻直付通 */
function handleAddZFTInfo(row: IInvestorsInfoVo) {
  /* 防止多次提交 */
  toggleState(true);
  putMerchantZftCreateInfo({ id: row.id })
    .then(res => {
      ElMessage.success(res.msg);
    })
    .catch(() => {})
    .finally(() => {
      toggleState(false);
    });
}
/* 投资商修改直付通 */
function handleUpdateZFTInfo(row: IInvestorsInfoVo) {
  /* 防止多次提交 */
  toggleState(true);
  putMerchantZftModifyInfo({ id: row.id })
    .then(res => {
      ElMessage.success(res.msg);
    })
    .catch(() => {})
    .finally(() => {
      toggleState(false);
    });
}
</script>

<style lang="scss" scoped>
/* layout-布局 */
.el-col {
  border-radius: 4px;
}

.mb10 {
  margin-bottom: 10px;
}
/* 关键：列表右侧操作按钮的对其 */
:deep(.el-space__item) {
  line-height: 15px;
}

.el-button.is-text + .el-button.is-text {
  margin-left: 0;
}

.bg-purple-dark {
  background: #99a9bf;
}

.bg-purple {
  background: #d3dce6;
}

.bg-purple-light {
  background: #e5e9f2;
}

.grid-content {
  border-radius: 4px;
  min-height: 36px;
}

.row-bg {
  padding: 10px 0;
  background-color: #f9fafc;
}

.handle-box {
  margin-bottom: 20px;
}

.handle-select {
  width: 120px;
}

.handle-input {
  width: 300px;
  display: inline-block;
}

.del-dialog-cnt {
  font-size: 16px;
  text-align: center;
}

.table {
  width: 100%;
  font-size: 14px;
}
.textAlignCenter {
  text-align: center;
}

/* 确定按钮的显示与隐藏 */
.displaybtn {
  display: none;
}

/* 提示图标设置 */
.icon-wzg-config {
  height: 30px;
  line-height: 30px;
}

.w-tag .el-tag {
  margin: 2px 5px;
}

.el-dropdown-link {
  cursor: pointer;
  color: var(--el-color-primary);
  display: flex;
  align-items: center;
}
</style>
